import Cookies, { type CookieAttributes } from "js-cookie";

const TokenKey = "token";

export function getToken(): string | null {
  const cookieToken = Cookies.get(TokenKey);
  if (cookieToken) return cookieToken;
  const storedToken = localStorage.getItem(TokenKey);
  try {
    return storedToken ? JSON.parse(storedToken) : null;
  } catch {
    return null;
  }
}

export function setToken(token: string, options?: CookieAttributes): void {
  Cookies.set(TokenKey, token, {
    ...options,
    expires: 7, // 强制7天过期避免永久存储
  });
}

export function removeToken() {
  localStorage.removeItem(TokenKey);
  return Cookies.remove(TokenKey);
}
